package org.advanced.shardpool;

import redis.clients.jedis.Client;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;

import java.util.Arrays;
import java.util.List;

/**
 * @author John.zhang
 * @version Id: ShardedJedisPool, v 1.0 2020/12/21 14:36 ZhiYong Exp $
 * redis监听器
 */
public class ShardedJedisPool {

    public static void main(String[] args) {
        JedisPoolConfig poolConfig = new JedisPoolConfig();

        // Redis服务器
        JedisShardInfo shardInfo1 = new JedisShardInfo("10.181.144.255", 6379);
        JedisShardInfo shardInfo2 = new JedisShardInfo("10.181.144.255", 6379);

        // 连接池
        List<JedisShardInfo> infoList = Arrays.asList(shardInfo1, shardInfo2);
        redis.clients.jedis.ShardedJedisPool jedisPool = new redis.clients.jedis.ShardedJedisPool(poolConfig, infoList);

        ShardedJedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            int max = 1000;
            for (int i = 0; i < max; i++) {
                jedis.set("k" + i, "" + i);
            }
            for (int i = 0; i < max; i++) {
                Client client = jedis.getShard("k" + i).getClient();
                System.out.println("取到值：" + jedis.get("k" + i) + "，" + "当前key位于：" + client.getHost() + ":" + client.getPort());
            }
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

}
